package com.yesep.learn.design.behavioral.strategy;

import com.yesep.learn.design.common.pojo.*;

import java.util.*;
import java.util.stream.*;

public class StrategyC implements IStrategy {
    @Override
    public String getLabel() {
        return "相同商品买二送一";
    }

    public double calculateTotalPrice(List<Goods> goodsList) {

        // 使用流和 Collectors.groupingBy 分组商品
        Map<String, List<Goods>> goodsMap = goodsList.stream().collect(Collectors.groupingBy(Goods::getName));
        double totalPrice = 0;
        // 遍历分组后的商品
        for (Map.Entry<String, List<Goods>> entry : goodsMap.entrySet()) {
            String name = entry.getKey();
            List<Goods> goods = entry.getValue();
            // 计算每种商品的数量
            int count = goods.size();
            // 每三件商品中有一件免费
            int freeItems = count / 3;
            int paidItems = count - freeItems;
            // 计算总价格
            double priceForThisItem = goods.get(0).getPrice() * paidItems;
            totalPrice += priceForThisItem;
        }
        System.out.printf("The %s %s calculate total price %s. \n", this.getClass().getSimpleName(), getLabel(), totalPrice);
        return totalPrice;
    }
}
